﻿define(function(require, export)
{
    var TIMER = null;
    var CALLBACK = {};
    var CALLBACK_LASTTIME = {};
    
    export.init = function()
    {
        TIMER = setInterval(onTimer, 10);
    };

    export.register = function(thisObj, callback, fps)
    {
        fps = parseInt(1000 / fps, 10);
        if(CALLBACK[fps] === undefined) 
        {
            CALLBACK[fps] = [];        
        }
        
        if(CALLBACK_LASTTIME[fps] == undefined)
        {
            CALLBACK_LASTTIME[fps] = 0;
        }
                        
        CALLBACK[fps].push(
            {
                'func' : callback,
                'callback' : function( interval )
                {
                    callback.apply(thisObj, [interval]);
                }
            }
        );
    };

    export.unregister = function(callback, fps)
    {
        fps = parseInt(1000 / fps, 10);
        var callbacks = CALLBACK[fps];
        
        if (!callbacks) 
        {
            return;
        }
        
        CALLBACK[fps] = callbacks.filter(function(item, index){
            if(item.func !== callback)
            {
                return true;
            }
            
            return false;
        });
    }

    var onTimer = function()
    {
        var curTime = Date.now();
        var lastTimes = CALLBACK_LASTTIME;
        for(var fps in lastTimes)
        {
            if (!lastTimes[fps])
            {
                CALLBACK_LASTTIME[fps] = curTime;
            }
            
            var interval = curTime - lastTimes[fps];
            
            if (fps <= interval) {
                CALLBACK_LASTTIME[fps] = curTime;
                CALLBACK[fps].forEach(function(item){
                    item.callback(interval);
                });
            }
        }
    };
});